//设置cookie
export const setCookie=(cname,cvalue,exTime=60*60*1000)=>{
    var d = new Date();
    d.setTime(d.getTime()+exTime);
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

// 获取cookie
export const getCookie=(cname)=>{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) 
    {
      var c = ca[i].trim();
      if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}

//检查cookie,暂时没有什么作用
export const checkCookie=()=>{
    var user=getCookie("username");
    if (user!=""){
        alert("欢迎 " + user + " 再次访问");
    }
    else {
        user = prompt("请输入你的名字:","");
          if (user!="" && user!=null){
            setCookie("username",user,30);
        }
    }
}

//获取所有的cookies
const getAllCookies=()=> {
    var cookies = document.cookie.split(/;\s/g);
    var cookieObj = {};
    cookies.forEach(function (item) {
        var key = item.split('=')[0];
        cookieObj[key] = item.split('=')[1];
    });
    return cookieObj;
}

//通过key来删除cookie
const clearCookieByKey=(key)=>{
    setCookie(key, "", -1);
}

//删除所有cookie
export const clearAllCookies=async ()=> {
    var keys = Object.keys(getAllCookies());
    keys.forEach(function (item) {
        clearCookieByKey(item);
    });
}

